/*
采用 getaddrinfo 传入主机名和服务名实现的 TCP 时间获取客户端。
**/

#include <define.h>
#include <error.h>
#include <wrapfunc.h>
#include <sockfunc.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <time.h>
#include <stdio.h>
#include <string.h>


int
main(int argc, char **argv) {
    if (argc != 2 && argc != 3)
        error_quit("usage: %s [host] servname", argv[0]);
    const char *host = NULL;
    const char *servname = NULL;
    if (argc == 2) {
        servname = argv[1];
    } else if (argc == 3) {
        host = argv[1];
        servname = argv[2];
    }

    int sockfd = Tcp_listen(host, servname, NULL);
    struct sockaddr_storage ss;
    socklen_t len;
    char buf[MAX_LINE];
    for (;;) {
        len = sizeof(struct sockaddr_storage);
        int connfd = Accept(sockfd, (struct sockaddr*)&ss, &len);
        error_msg("new connection from %s", sock_ntop((struct sockaddr*)&ss, len));

        time_t tick;
        time(&tick);
        snprintf(buf, sizeof(buf), "%.24s", ctime(&tick));
        Write(connfd, buf, strlen(buf));
        Close(connfd);
    }

    Close(sockfd);
    return 0;
}
